<template>
  <card title="登录" btn-text="返回首页" :onBack="backToHome">
    <el-form :rules="loginRules" ref="loginForm" :model="loginForm" label-width="80px" label-position="left">
      <el-form-item label="邮箱" prop="account">
        <el-input v-model="loginForm.account" placeholder="用户名/邮箱" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" />
      </el-form-item>
      <div class="flex justify-center">
        <el-button type="primary" @click="login" style="width: 150px; margin-bottom: 10px">登录</el-button>
      </div>
      <div class="flex justify-center">
        <el-button type="text" @click="$router.push({ name: 'register' })">没有账号? 去注册</el-button>
      </div>
    </el-form>
  </card>
</template>

<script>
import { login } from "@/api/user";
import regex from "@/utils/regex";

export default {
  name: "Login",
  data() {
    // 检查密码: 键盘能输入的所有字符或符号{6, 16}
    const checkPassword = (rule, val, callback) => {
      if (regex.password.test(val)) {
        return callback();
      }
      return callback(new Error("密码有误"));
    };
    return {
      loginForm: {
        account: "",
        password: "",
      },
      loginRules: {
        account: [{ required: true, message: "账号不能为空", trigger: "blur" }],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { trigger: "blur", validator: checkPassword },
        ],
      },
    };
  },
  methods: {
    // 返回首页
    backToHome() {
      this.$router.push({ name: "home" });
    },

    // 处理登录: 先检查数据, 然后登录
    login() {
      this.$refs.loginForm.validate(async (isPassed) => {
        if (!isPassed) {
          this.$message.error("数据格式有误,请检查后再次尝试");
          return;
        }
        const res = await login(this.loginForm);
        if (res.success) {
          this.$router.push({ name: "home" });
          this.$message.success("登录成功");
          this.$store.commit("user/login", res.data);
          return;
        }
        this.$message.error("登录失败:" + res.msg);
      });
    },
  },
};
</script>
